#include "ResMgrPch.h"

#include "MeshBase.h"

#include "RenderFacade.h"
#include "RenderUtil.h"
#include "BoneInfo.h"

MeshBase::MeshBase(void)
: m_pVertices( NULL )
, m_pIndices( NULL )
, m_pIB( NULL )
, m_pVB( NULL )
, m_uVertexCount( 0 )
, m_uIndexCount( 0 )
{
}

MeshBase::~MeshBase(void)
{
	SAFE_RELEASE( m_pVB );
	SAFE_RELEASE( m_pIB );

	SAFE_DELETE_ARRAY( m_pVertices );
	SAFE_DELETE_ARRAY( m_pIndices );

	std::map<std::string, Material *>::iterator it = m_materialMap.begin();
	for( ; it != m_materialMap.end(); it++ )
	{
		Material * cur = it->second;
		SAFE_DELETE( cur );
	}

	m_materialMap.clear();
}

BOOL MeshBase::CreateVB()
{
	int size = m_uVertexCount * m_vertexType.m_size;
	DWORD usage = D3DUSAGE_WRITEONLY;  

	HRESULT hr = RenderFacade::GetInstance()->CreateVertexBuffer( size, usage, m_vertexType.m_fvf, D3DPOOL_DEFAULT, &m_pVB, NULL ); 
	if( SUCCEEDED( hr ) )
	{
		void* pVertices = NULL;
		if( SUCCEEDED( m_pVB->Lock( 0, size, (void**)&pVertices, 0 ) ) )
		{
			memcpy_s( pVertices, size, m_pVertices, size );
		}
		m_pVB->Unlock();

		return TRUE;
	}

	return FALSE;
}

BOOL MeshBase::CreateIB()
{
	int size = sizeof( DWORD ) * m_uIndexCount;
	DWORD usage = D3DUSAGE_WRITEONLY;  

	HRESULT hr = RenderFacade::GetInstance()->CreateIndexBuffer( size, usage, D3DFMT_INDEX32, D3DPOOL_DEFAULT, &m_pIB, NULL );
	if( SUCCEEDED( hr ) )
	{
		void* pIndices = NULL;
		if( SUCCEEDED( m_pIB->Lock( 0, size, (void**)&pIndices, 0 ) ) )
		{
			memcpy_s( pIndices, size, m_pIndices, size );
		}
		m_pIB->Unlock();

		return TRUE;
	}

	return FALSE;
}

void MeshBase::DrawNormal()
{
	std::vector<Vector3> points;

	int renderGroupCount = (int)m_renderGroupList.size();
	for( int cnt = 0; cnt < renderGroupCount; cnt++ )
	{
		int startIndex = m_renderGroupList[cnt].m_startIndex; 
		int indexCount = m_renderGroupList[cnt].m_indexCount;

		Vector3 pos, normal;
		for( int iCnt = startIndex; iCnt < startIndex + indexCount; iCnt++ )
		{
			DWORD vertexIndex = m_pIndices[iCnt];

			switch( m_vertexType.m_type )
			{
			case VertexType::POS3NUV:
				{
					VertexPos3NUV* tempVertices = (VertexPos3NUV*)m_pVertices; 
					pos = tempVertices[vertexIndex].m_pos;
					normal = tempVertices[vertexIndex].m_normal;
				}
				break;
			}

			points.push_back(pos);
			points.push_back(pos + normal/10.f);
		}
	}

	if( points.size() > 0 )
	{
		RenderUtil::GetInstance()->RenderLineList( points, 0xff00ffff );
	}
}